/* ******************************************************************
 * This file is part of the escal project and distributed under the 
 * terms of the GNU General Public License Version 3
 * Copyright (C) 2008 Epocher (xijiaosdq@gmail.com)
 * See COPYING file for licensing information.
 ********************************************************************/

#include "escal_settings.h"
#include <QtDebug>
#include <stdlib.h>
#include <QStringList>
#include <QSize>

EscalSettings::EscalSettings(const QString & organization, const QString 
		& application ,QObject * parent)
	:QObject(parent), settings(organization,application ,this)
{
	buildDefaultValues();
	checkSettings();
};

EscalSettings::EscalSettings(const QString & fileName, QSettings::Format format,
		QObject * parent)
	:QObject(parent), settings(fileName, format, this)
{
	buildDefaultValues();
	checkSettings();
};

QVariant EscalSettings::value(const QString & key, const QVariant 
		& defaultValue) const
{
	return settings.value(key, defaultValue);
};

QVariant EscalSettings::defaultValue(const QString & key) const
{
	return defaultMap[key];
};

void EscalSettings::setValue(const QString & key, const QVariant & value ){
	settings.setValue(key, value);
	if(key=="Folder/DownloadFolderList"){
		emit foldersChanged();
	}
};

void EscalSettings::buildDefaultValues(){
	defaultMap["Folder/DownloadFolderList"]=
		QStringList(QString(getenv("HOME")));
	defaultMap["eGear/StartTaskAfterAdded"]=true;
	defaultMap["eGear/DefaultThreadNum"]=6;
	defaultMap["eGear/MaxTaskRunning"]=6;
	defaultMap["eGear/WatchClipboard"]=true;
	defaultMap["MainWindowSize"]=QSize(800, 500);
	defaultMap["Network/UseProxy"]=false;
	defaultMap["Network/ProxyServerAddr"]=QString();
	defaultMap["Network/ProxyServerPort"]=80;
	{
		QVariantList sizes;
		sizes << 200 << 400;
		defaultMap["ViewSplitterSizes2"]=sizes;
	}
	{
		QStringList postfixs;
		postfixs << ".rar" << ".bz2" << ".gz" << ".zip" << ".7z"
			<< ".iso" << ".tar" << ".tgz" << ".rpm" << ".deb"
			<< ".avi" << ".rm" << ".rmvb" << ".wmv" << ".exe"
			<< ".lzma" << ".torrent";
		defaultMap["eGear/WatchedLinksuffixList"]=postfixs;
	}
};

void EscalSettings::checkSettings(){
	qDebug() << "EscalSettings::checkSettings()";
	QMap<QString, QVariant>::iterator i=defaultMap.begin();
	while(i != defaultMap.end()){
		qDebug() << i.key();
		if(settings.value(i.key())==QVariant()){
			settings.setValue(i.key(), i.value());
		}
		++i;
	}
};
